<template>
  <el-row align="middle" class="align-items">
    <el-col :span="12">
      <div  class="mediatitle">
        视频列表
        <span v-if="tableData.total">（{{tableData.total}}）</span>
        <el-input placeholder="请输入视频名称"
                  v-model.trim="queryList.keyword"
                  clearable
                  class="input-w mr10" size="small"
                  @clear="handleFilterSeries"
                  @keyup.enter="handleFilterSeries"
        >
          <template #append>
            <el-button @click="handleFilterSeries">
              <el-icon>
                <search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </el-col>
    <el-col :span="12">
      <div align="right">
        <span v-if="currentCorpid == dataInfo.corpid">
          <span v-if="isedit">
            <el-button type="warning" size="mini" @click="handleSeriesBatchSort">
              <el-icon>
                <Sort />
              </el-icon>
              批量排序
            </el-button>
            <el-button type="primary" size="mini" @click="handleCreateSeries">
              <el-icon>
                <plus />
              </el-icon>
              添加视频
            </el-button>
          </span>
        </span>
      </div>
    </el-col>
    <el-col :span="24">
      <el-table :data="tableData.listData" v-loading="isloading" border max-height="300" class="tabledoud">
        <el-table-column label="封面图" width="80" align="center">
          <template #default="{row}">
            <el-image
                    v-if="row.thumbs && row.thumbs.length > 0"
                    :src="row.thumbs[0].isself == 1 ? row.thumbs[0].viewurl + '&width=60px' : row.thumbs[0].viewurl"
                    :preview-src-list="imgSrcList"
                    :initial-index="initialIndex(row.thumbs[0].viewurl)"
                    fit="scale-down"
                    style="height:50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" show-overflow-tooltip>
          <template #default="{row}">
            <a class="txtclamp" href="javascript:;" @click.prevent="handleClickSeriesInfo(row.seriesid)">{{row.name}}</a>
          </template>
        </el-table-column>
        <el-table-column label="视频ID" prop="seriesid" width="120"/>
        <el-table-column label="类型/状态" width="100" >
          <template #default="{row}">
            <span v-if="row.tplid == '4426c5688ed111ecb86d00163e30b2e1'">
              <div>事件直播</div>
              <div class="mt10">
                <span v-if="row.extends && row.extends.livestate">
                  <span v-if="row.extends.livestate =='pending'" style="color: #ee9900">等待直播</span>
                  <span v-else-if="row.extends.livestate == 'live'" style="color: #63a35c">直播中</span>
                  <span v-else-if="row.extends.livestate == 'end'" style="color: red">直播结束</span>
                  <span v-else>-</span>
                </span>
                <span v-else>-</span>
              </div>
            </span>
            <span v-else-if="row.tplid == 'db5416e88ed111ecb86d00163e30b2e1'">
              <div>预约直播</div>
              <div class="mt10">
                <span v-if="row.extends && row.extends.livestate">
                  <span v-if="row.extends.livestate =='pending'" style="color: #ee9900">等待直播</span>
                  <span v-else-if="row.extends.livestate == 'live'" style="color: #63a35c">直播中</span>
                  <span v-else-if="row.extends.livestate == 'end'" style="color: red">直播结束</span>
                  <span v-else>-</span>
                </span>
                <span v-else>-</span>
              </div>
            </span>
            <span v-else-if="row.tplid == 'bcf23e6ca1ac11ec9003ecf4bbdc75f0'">
              <div>频道直播</div>
              <div class="mt10">
                <span v-if="row.extends && row.extends.livestate">
                  <span v-if="row.extends.livestate =='pending'" style="color: #ee9900">等待直播</span>
                  <span v-else-if="row.extends.livestate == 'live'" style="color: #63a35c">直播中</span>
                  <span v-else-if="row.extends.livestate == 'end'" style="color: red">直播结束</span>
                  <span v-else>-</span>
                </span>
                <span v-else>-</span>
              </div>
            </span>
            <span v-else-if="row.tplid == 'dc56caf0e62811ecafd8ecf4bbc33d44'">
              <div>点播音频</div>
              <div>-</div>
            </span>
            <span v-else>
              <div>点播视频</div>
              <div class="mt10">-</div>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="画面" width="80">
          <template #default="{row}">
            <span v-if="row.extends && row.extends.videolayout">
              <span v-if="row.extends.videolayout == 'horizontal'">横屏</span>
              <span v-else-if="row.extends.videolayout == 'vertical'">竖屏</span>
              <span v-else-if="row.extends.videolayout == 'square'">方屏</span>
              <span v-else-if="row.extends.videolayout == 'unknown'">未知</span>
              <span v-else>-</span>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="主播信息" width="100">
          <template #default="{row}">
            <span v-if="row.extends && row.extends.anchors && row.extends.anchors.length > 0">
              <div v-for="anchor in row.extends.anchors" :key="anchor.idnum">
                {{anchor.fullname}}
              </div>
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="70px">
          <template #default="{row}">
            <span v-if="row.state == 0">未提交</span>
            <span v-else-if="row.state == 1">审核中</span>
            <span v-else-if="row.state == 2">审核通过</span>
            <span v-else-if="row.state == 3">审核失败</span>
            <span v-else-if="row.state == 4">免审</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="付费状态" :width="80">
          <template #default="{row}">
            <span v-if="row.paytype === 1" style="color: #F56C6C">付费</span>
            <span v-else style="color: #67C23A">免费</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="60" fixed="right" align="center">
          <template #default="{row}">
            <series-resort
                    :downdisabled="!isedit || row.topno > 1"
                    :updisabled="!isedit || row.topno > 1"
                    :row="row"
                    @reloadSeries="getSeriesList"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" :width="160">
          <template #default="{row}">
            <span v-if="currentCorpid == dataInfo.corpid && isedit">
              <series-to-top
                :row="row"
                :edit-status="isedit"
                @reloadSeries="getSeriesList"
              />
              <el-button :disabled="!(row.state == 2 || row.state == 4)" type="text" size="mini" @click="handleSeriesOnOff(row)">
                <span v-if="!(row.state == 2 || row.state == 4)">
                  <span v-if="row.inuse == 1">下线</span>
                  <span v-else>上线</span>
                </span>
                <span v-else>
                  <span v-if="row.inuse == 1" style="color: #ee9900">下线</span>
                <span v-else style="color: #00C653">上线</span>
                </span>
              </el-button>
              <br/>
              <el-button type="text" size="mini" @click="handleToUpdateSeries(row)" :disabled="row.state == 1">编辑</el-button>
              <el-button :disabled="!(row.state == 0 || row.state == 3)" type="text" size="mini" @click.stop="handleReview(row)">申请审核</el-button>
              <series-delete-button :row="row" @reloadSeries="getSeriesList"/>
            </span>
            <span v-else>
              <series-to-top
                :row="row"
                :edit-status="false"
                @reloadSeries="getSeriesList"
              />
              <el-button type="text" size="mini" :disabled="true">
                <span v-if="row.inuse == 1">下线</span>
                <span v-else>上线</span>
              </el-button>
              <br/>
              <el-button type="text" size="mini" :disabled="true">编辑</el-button>
              <el-button type="text" size="mini" :disabled="true">申请审核</el-button>
              <series-delete-button :row="row" :disabled="true" @reloadSeries="getSeriesList"/>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="24" class="mt15">
      <table-pagination
              v-if="tableData.total > 0"
              :query-list="queryList"
              :total="tableData.total"
              @pagination="getSeriesList"
      />
    </el-col>
  </el-row>
  <create-series
    ref="createSeriesDialogRef"
    :create-series-dialog-visible="createSeriesVisible"
    :create-series-dialog-title="createSeriesTitle"
    :create-series-dialog-form-data="createSeriesFormData"
    @handleCancelCreateSeriesDialog="cancelCreateSeriesDialog"
    @reloadSeriesList="getSeriesList"
    @handleVideoPlay="handleVideoPlay"
  />
  <series-batch-sort
     ref="seriesBatchSortRef"
    :mediaid="dataInfo.mediaid"
    :is-visible="isVisible"
    @handleCloseDialog="handleCloseDialog"
     @reloadSeriesList="getSeriesList"
  />
</template>

<script>
  import {ref, reactive, computed, toRef, nextTick, defineAsyncComponent} from 'vue'
  import {useRouter, useRoute} from 'vue-router'
  import {Search, Plus} from '@element-plus/icons'
  import {getSeries, seriesOnOff} from "@/api/series/series";
  import TablePagination from "@/views/public/TablePagination";
  import CreateSeries from "./CreateSeries";
  import {ElMessageBox, ElMessage} from 'element-plus'
  import {seriesReview} from "@/api/media/review";
  import SeriesResort from "@/components/Common/SeriesResort";
  import SeriesToTop from "@/components/Common/SeriesToTop";
  import SeriesDeleteButton from '@/components/Common/SeriesDeleteButton'

  export default {
    name: "index",
    components: {
      Search,
      Plus,
      TablePagination,
      CreateSeries,
      SeriesResort,
      SeriesToTop,
      SeriesDeleteButton,
      'SeriesBatchSort': defineAsyncComponent(() => import('@/components/Common/Series/SeriesBatchSort'))
    },
    props: {
      dataInfo: {
        type: Object,
        required: true
      },
      currentCorpid: {
        type: Number,
        required: true
      },
      query: {
        type: Object
      },
      isedit: {
        type: Boolean,
        default: false
      }
    },
    emits: ['handleVideoPlay'],
    setup(props, context) {
      const router = useRouter()
      const route = useRoute()
      const localQuery = toRef(props, 'query')
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        mediaid: undefined,
        keyword: undefined
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const isloading = ref(null)
      const imgSrcList = ref([])
      /** 新建子集相关参数开始 **/
      const createSeriesVisible = ref(false)
      const createSeriesFormData = reactive({
        mediaid: undefined,
        mediatype: undefined,
        groupid: undefined,
        paytype: 0
      })
      const createSeriesTitle = ref('')
      const createSeriesDialogRef = ref(null)
      /** 新建子集相关参数结束 **/
      const hasseriesnextpage = ref(false)

      const initialIndex = computed(() => {
        return (viewurl) => {
          return imgSrcList.value.findIndex(d => d === viewurl)
        }
      })

      const getSeriesList = () => {
        // isloading.value = true
        getSeries(queryList).then(response => {
          isloading.value = false
          if (response.errcode == 0) {
            const {total, list, hasnextpage} = response.data
            hasseriesnextpage.value = !!hasnextpage
            tableData.listData = list
            tableData.total = total
            imgSrcList.value = []
            tableData.listData.forEach(row => {
              if (row.thumbs && row.thumbs.length > 0) {
                imgSrcList.value.push(row.thumbs[0].viewurl)
              }
            })
          }
        })
      }
      const init = () => {
        if (!queryList.mediaid) {
          queryList.mediaid = props.dataInfo.mediaid
          queryList.mediaid
          getSeriesList()
        }
      }
      const handleClickSeriesInfo = (seriesid) => {
        localQuery.value.seriesid = seriesid
        if (route.path.indexOf('/mediashare/share') !== -1) {
          // router.push({path: '/mediashare/media/series/detail', query: localQuery.value})
          router.push({path: '/mediashare/share/medias/series/detail', query: localQuery.value})
        } else if (route.path.indexOf('/mediashare/get') !== -1) {
          // router.push({path: '/fromcorpmedia/media/series/detail', query: localQuery.value})
          router.push({path: '/mediashare/get/medias/series/detail', query: localQuery.value})
        } else if (route.path.indexOf('/package/contentproject') !== -1) {
          router.push({path: '/package/contentproject/media/series/detail', query: localQuery.value})
        } else if (route.path.indexOf('/medias/list/all') !== -1) {
          router.push({path: '/medias/list/all/detail/series/detail', query: localQuery.value})
        } else if (route.path.indexOf('/medias/list/liveroom') !== -1) {
          router.push({path: '/medias/list/liveroom/detail/series/detail', query: localQuery.value})
        } else {
          router.push({path: '/media/series/detail', query: localQuery.value})
        }
      }
      const handleCreateSeries = () => {
        createSeriesFormData.mediaid = props.dataInfo.mediaid
        createSeriesFormData.groupid = props.dataInfo.groupid
        createSeriesFormData.mediatype = props.dataInfo.mediatype
        createSeriesFormData.paytype = props.dataInfo.paytype
        createSeriesTitle.value = props.dataInfo.name + ' 下新建视频'
        createSeriesVisible.value = true
        nextTick(() => {
          createSeriesDialogRef.value.init()
        })
      }
      const cancelCreateSeriesDialog = () => {
        createSeriesVisible.value = false
      }
      const handleToUpdateSeries = (row) => {
        localQuery.value.seriesid = row.seriesid
        localQuery.value.isedit = 1
        if (route.path.indexOf('/mediashare/share') !== -1) {
          // router.push({path: '/mediashare/media/series/detail', query: localQuery.value})
          router.push({path: '/mediashare/share/medias/series/detail', query: localQuery.value})
        } else if (route.path.indexOf('/mediashare/get') !== -1) {
          // router.push({path: '/fromcorpmedia/media/series/detail', query: localQuery.value})
          router.push({path: '/mediashare/get/medias/series/detail', query: localQuery.value})
        } else {
          router.push({path: '/media/series/detail', query: localQuery.value})
        }
      }
      const handleSeriesOnOff = (row) => {
        const inuse = row.inuse == 1 ? 0 : 1
        if (inuse == 1) {
          ElMessageBox.confirm('确定要将视频 ' + row.name + ' 上线吗？', '视频上线操作', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            seriesOnOff({seriesids: [row.seriesid], inuse: inuse}).then(response => {
              if (response.errcode == 0) {
                ElMessage({type: 'success', message: response.msg, duration: 2000})
                getSeriesList()
              }
            })
          }).catch(() => {})
        } else {
          ElMessageBox.prompt('请输入视频下线原因', '视频下线操作',{
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '请输入下线原因',
            inputValidator: (value) => {
              if (value) {
                return true
              } else {
                return false
              }
            },
            inputErrorMessage: '请输入下线原因'
          }).then((val) => {
            seriesOnOff({seriesids: [row.seriesid], inuse: inuse, comments: val.value}).then(response => {
              if (response.errcode == 0) {
                ElMessage({type: 'success', message: response.msg, duration: 2000})
                getSeriesList()
              }
            })
          })
        }
      }
      const handleVideoPlay = (row) => {
        context.emit('handleVideoPlay', row)
      }
      /** 子集申请审核 **/
      const handleReview = (row) => {
        ElMessageBox.confirm(
          '确定申请视频 ' + row.name + ' 进行审核吗？',
          '视频审核',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          seriesReview({seriesids:[row.seriesid]}).then(response => {
            if( response.errcode == 0 ){
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              getSeriesList()
            }else{
              console.log(response)
            }
          })
        }).catch(() => {})
      }
      const handleFilterSeries = () => {
        queryList.page = 1
        getSeriesList()
      }

      const seriesBatchSortRef = ref(null)
      const isVisible = ref(false)
      const handleCloseDialog = () => {
        isVisible.value = false
      }
      const handleSeriesBatchSort = () => {
        isVisible.value = true
        nextTick(() => {
          seriesBatchSortRef.value.handleGetSeries()
        })
      }

      return {
        queryList,
        tableData,
        isloading,
        init,
        imgSrcList,
        initialIndex,
        handleClickSeriesInfo,
        getSeriesList,
        createSeriesVisible,
        createSeriesFormData,
        createSeriesTitle,
        cancelCreateSeriesDialog,
        handleCreateSeries,
        createSeriesDialogRef,
        handleToUpdateSeries,
        handleSeriesOnOff,
        handleFilterSeries,
        handleVideoPlay,
        handleReview,
        hasseriesnextpage,
        isVisible,
        handleCloseDialog,
        handleSeriesBatchSort,
        seriesBatchSortRef
      }
    }
  }
</script>

<style lang="scss">
  // .mediatitle{
  //   margin-top: 0;
  //   &:first{
  //     margin-top: 0;
  //   }
  //   display:inline-block;
  //   margin-right: 10px;
  //   margin-bottom: 16px;
  //   font-weight: bold;
  //   font-size: 18px;
  // }
</style>
<style lang="scss">

</style>
